package com.np.adapterdemo1;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts;
import android.provider.Settings;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;

public class SimpleCursorAdapterActivity extends ListActivity {

    private final int PERMISSION_READ_CONTACTS = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 检查权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            // 请求权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, PERMISSION_READ_CONTACTS);
        }

        // 获取一个指向系统通讯录数据库的 Cursor 对象并获得数据来源
        Cursor cur = getContentResolver().query(Contacts.People.CONTENT_URI, null, null, null, null);
        startManagingCursor(cur);

        ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.activity_simple_cursor_adapter, cur, new String[]{Contacts.People.NAME, Contacts.People.NAME}, new int[]{R.id.title, R.id.info});
        setListAdapter(adapter);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_READ_CONTACTS:
                // 如果请求被取消，则结果数组为空
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 权限被授予，可以执行相应的操作
                } else {
                    // 权限被用户拒绝，需要引导用户去设置页面手动开启
                    // 可以选择引导用户到应用的设置页面
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", getPackageName(), null);
                    intent.setData(uri);
                    startActivity(intent);
                }
                break;
        }
    }
}